﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Common;
using Ice.Toolkit.Data.Entity;
using Ice.Toolkit.Data.ILInvoker;

namespace Ice.Toolkit.Data.Sql
{
    internal class DeleteBuilder<T> : BuilderBase<T> where T : EntityBase<T>, new()
    {
        private String _sqlTemplate = "DELETE [{0}] ";
        private Expression<Func<T, bool>> _expression;
        private T _instance;

        public DeleteBuilder(DataContext dataContext)
            : base(dataContext)
        { 
        
        }

        public DeleteBuilder(DataContext dataContext, T instance)
            : base(dataContext)
        {
            _instance = instance;
        }

        public DeleteBuilder(DataContext dataContext, Expression<Func<T, bool>> expression)
            : base(dataContext)
        {
            _expression = expression;
        }

        public override String Build()
        {
            var table = EntityAttribManager.Get<T>().Talbe;

            SQLText = String.Format(_sqlTemplate, table.TableName);

            if (_expression != null)
            {
                var sqlWhere = new SqlWhere<T>(_expression);
                SQLText += " WHERE " + sqlWhere.SqlWhereText;


                var loop = sqlWhere.Columns.Count;

                for (var i = 0; i < loop; i++)
                {
                    AddParameter(sqlWhere.Columns[i], sqlWhere.Values[i]);
                }
            }
            else if (_instance != null)
            {
                var pName = EntityAttribManager.Get<T>().IdentityPropertyName;

                SQLText += String.Format(" WHERE [{0}] = @{0}", pName);

                AddParameter(pName, PropertyAccessor<T>.Get(_instance, pName));
            }

            return SQLText;
        }
    }
}
